package com.wenzi.rule.verification.actuator;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wenzi.rule.verification.base.RuleConfig;
import com.wenzi.rule.verification.exception.RuleValidException;
import com.wenzi.rule.verification.form.Form;
import com.wenzi.rule.verification.form.FormUtil;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.List;
import java.util.Map;


public interface Actuator {
    static final Log LOG = LogFactory.get(Actuator.class);
    public String getType();

    public Map<String,List<RuleConfig>> getRuleConfig(String configName);

    default public void execute(String configName, Object form, BeanResolver resolver){
        Map<String, List<RuleConfig>> ruleConfig = getRuleConfig(configName);
        if(ruleConfig == null || form == null){
            return;
        }

        StandardEvaluationContext context = new StandardEvaluationContext();
//        context.setBeanResolver(resolver);
        ruleConfig.forEach((key,ruleConfigs)->{
            List<Form> forms = FormUtil.parseForm(form, key);
            if (CollectionUtil.isEmpty(forms)){
                return;
            }

            forms.forEach(form1 -> {
                form1.setVariableFor(context);
                ruleConfigs.forEach(t->{
                    if (!t.getEnable()){
                        LOG.info("The rule is not enabled:{}",t.toString());
                        return;
                    }

                    try {
                        t.getRule().doRule(context);
                    }catch (RuleValidException e){
                        LOG.error(e,"Rule validation exceptions,message:{}",e.getMessage());
                        throw e;
                    }
                });
            });
        });
    }
}
